package com.mzba.place.ui;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.google.gson.Gson;
import com.mzba.place.BasicActivity;
import com.mzba.place.PlaceApplication;
import com.mzba.place.R;
import com.mzba.place.db.SafeCardTable;
import com.mzba.place.entity.ReportEntity;
import com.mzba.place.entity.SafecardEntity;
import com.mzba.place.entity.TXWeiboResultEntity;
import com.mzba.place.utils.AccessTokenKeeper;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.ScreenShot;
import com.mzba.place.utils.ShareUtils;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
import com.mzba.place.utils.Utils;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.open.HttpStatusException;
import com.tencent.open.NetworkUnavailableException;
import com.tencent.tauth.Constants;
import com.tencent.tauth.IRequestListener;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.tencent.weibo.sdk.android.api.WeiboAPI;
import com.tencent.weibo.sdk.android.component.Authorize;
import com.tencent.weibo.sdk.android.component.sso.AuthHelper;
import com.tencent.weibo.sdk.android.component.sso.OnAuthListener;
import com.tencent.weibo.sdk.android.component.sso.WeiboToken;
import com.tencent.weibo.sdk.android.model.AccountModel;
import com.tencent.weibo.sdk.android.model.BaseVO;
import com.tencent.weibo.sdk.android.model.ModelResult;
import com.tencent.weibo.sdk.android.network.HttpCallback;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.AccountAPI;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.net.RequestListener;

/**
 * 
 * @author 06peng
 * 
 */
public class SafecardActiviy extends BasicActivity implements Callback,HttpCallback{

	private SafecardEntity safecard;
	private TextView precent_tv;
	private TextView address_tv;
	private TextView type1_tv;
	private TextView type2_tv;
	private TextView type3_tv;
	private TextView type4_tv;
	private TextView empty_tv;
	private TextView desctiption_tv;

	public MapView mMapView = null;
	private MapController mMapController = null;
	private Handler handler;

	private final int init_safe_cards = 1;
	private final int init_reports = 2;
	private final int create_safe_card = 3;

	private final int menu_sina = 5;
	private final int menu_qq = 6;
	private final int menu_weixin_contact = 7;
	private final int menu_weixin_friend = 8;
	private final int menu_tengxun = 9;
	
	private final int task_photo_origin_url =10;
	private final int task_photo_thumb_url=11;
	private Drawable marker1;
	private Drawable marker2;
	private Drawable marker3;
	private Drawable marker4;

	public PlaceApplication app;
	public LocationClient mLocClient;

	private double current_latitude;
	private double current_longitude;
	/**
	 * 微信
	 */
	private IWXAPI api;
	private Weibo mSinaWeibo;
	private Oauth2AccessToken accessToken;
	/**
	 * qq空间
	 */
	private Tencent mTencent;
	/**
	 * 
	 */
	private WeiboAPI tx_weiboAPI;// 微博相关API
	private StatusesAPI sinaWeiboAPI;
	/**
	 * 分享的url
	 */
	private String share_url;
	/**
	 * 分享的内容
	 */
	String content ;
	/**
	 * 分享的图片
	 */
	Bitmap thumbBmp;
	/**
	 * 新浪微博分享的图片地址
	 */
	String photo_url = AppContext.getSDPath()+"pu.png";
	
	String weibo_name =" @shenbiananquan";
	
	private String md5;
	
	WeakReference<Bitmap>	photoOriginUrlBitmap;
	WeakReference<Bitmap>	photoThumbUrlBitmap;
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.safe_card);
		handler = new Handler(this);
		api = WXAPIFactory.createWXAPI(this, AppContext.WX_APPID, false);
		api.registerApp(AppContext.WX_APPID);
		// api.handleIntent(getIntent(), this);
		api = WXAPIFactory.createWXAPI(this, AppContext.WX_APPID);
		initQQZoom();
		marker1 = getResources().getDrawable(R.drawable.ic_map_marker_01);
		marker2 = getResources().getDrawable(R.drawable.ic_map_marker_02);
		marker3 = getResources().getDrawable(R.drawable.ic_map_marker_03);
		marker4 = getResources().getDrawable(R.drawable.ic_map_marker_04);

		app = (PlaceApplication) getApplication();
		if (app.mBMapManager == null) {
			app.mBMapManager = new BMapManager(this);
			app.mBMapManager.init(PlaceApplication.strKey, new PlaceApplication.MyGeneralListener());
		}
		app.getMyListener().setHander(handler);
		mLocClient = app.mLocationClient;
		
		precent_tv = (TextView) findViewById(R.id.safe_percent);
		address_tv = (TextView) findViewById(R.id.address_tv);
		type1_tv = (TextView) findViewById(R.id.safe_type1);
		type2_tv = (TextView) findViewById(R.id.safe_type2);
		type3_tv = (TextView) findViewById(R.id.safe_type3);
		type4_tv = (TextView) findViewById(R.id.safe_type4);
		empty_tv = (TextView) findViewById(R.id.safe_empty);
		desctiption_tv = (TextView) findViewById(R.id.safe_describtion);
		
		empty_tv.setVisibility(View.GONE);
		findViewById(R.id.safe_map_layout).setVisibility(View.GONE);

		mMapView = (MapView) findViewById(R.id.bmapView);
		mMapController = mMapView.getController();
		mMapController.enableClick(false);
		mMapController.setZoom(14);
		mMapController.setScrollGesturesEnabled(false);
		mMapController.setZoomGesturesEnabled(false);
		mMapController.enableClick(false);
		mMapView.setDoubleClickZooming(false);
		mMapView.setBuiltInZoomControls(false);
		mMapView.setDoubleClickZooming(false);
		actionBar.show();
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(R.string.fragment_safecard);
		setSupportProgressBarIndeterminateVisibility(false);
		
		md5 = getIntent().getStringExtra("md5");
		if (StringUtil.isNotBlank(md5)) {
			UICore.eventTask(this, this, init_safe_cards, null, true);
		} else {
			menuMyPosition();
		}
	}

	

	/**
	 * qq空间注册id
	 */
	private void initQQZoom() {
		mTencent = Tencent.createInstance(UrlConfig.qq_appid,
				this.getApplicationContext());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (menu != null) {
			menu.clear();
			SubMenu subMenu = menu.addSubMenu("分享");
			subMenu.add(Menu.NONE, menu_sina, Menu.NONE, "分享到新浪微博");
			subMenu.add(Menu.NONE, menu_qq, Menu.NONE, "分享到QQ空间");
			subMenu.add(Menu.NONE, menu_weixin_contact, Menu.NONE, "分享到微信");
			subMenu.add(Menu.NONE, menu_weixin_friend, Menu.NONE, "分享到朋友圈");
			subMenu.add(Menu.NONE, menu_tengxun, Menu.NONE, "分享到腾讯微博");

			MenuItem subMenuItem = subMenu.getItem();
			subMenuItem.setIcon(R.drawable.icon_share);
			subMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
					| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (safecard!=null) {
			share_url = UrlConfig.safe_card_share + safecard.getMd5();
			content = "#身边安全#" + "火速围观这里(" + safecard.getAddress() + ")，没想到周边的扒手和色狼还真不少呀，各位小伙伴们怎么看？更多详情猛击";
//			WeakReference<Bitmap> wbit = new WeakReference<Bitmap>(
//					ScreenShot.takeScreenShot(SafecardActiviy.this));

//			thumbBmp = Bitmap.createScaledBitmap(photoOriginUrlBitmap.get(), 120, 120, true);
		

//			if (wbit.get() != null) {
//				wbit.get().recycle();
//			}
		}
		switch (item.getItemId()) {
		case android.R.id.home:
			setResult(RESULT_OK, getIntent());
			finish();
			break;
		case menu_sina:
			if (StringUtil.isBlank(safecard.getMd5())) {
				Toast.makeText(this, "无法分享，请重新生成安全卡！", Toast.LENGTH_LONG).show();
			} else {
				accessToken = AccessTokenKeeper.readAccessToken(SafecardActiviy.this);
				 content = content+share_url+"&#160"+" @身边安全调查员";
				if (accessToken.isSessionValid()) {
					UICore.eventTask(SafecardActiviy.this, SafecardActiviy.this, menu_sina, null, true);
				} else {
					mSinaWeibo = Weibo.getInstance(UrlConfig.sina_appkey, UrlConfig.redirect_url);
					mSinaWeibo.authorize(SafecardActiviy.this, new SinaOAuthListener());
				}
				//
			}
			break;
		case menu_qq:
			if (StringUtil.isBlank(safecard.getMd5())) {
				Toast.makeText(this, "无法分享，请重新生成安全卡！", Toast.LENGTH_LONG)
						.show();
			} else {
				onQQLogin();
			}
			break;
		case menu_weixin_contact:
			content = "火速围观这里(" + safecard.getAddress()+ ")，没想到周边的扒手和色狼还真不少呀。";
			if (StringUtil.isBlank(safecard.getMd5())) {
				Toast.makeText(this, "无法分享，请重新生成安全卡！", Toast.LENGTH_LONG)
						.show();
			} else {
				UICore.eventTask(SafecardActiviy.this, SafecardActiviy.this, menu_weixin_contact, null, true);
			}

			break;
		case menu_weixin_friend:
			content = "火速围观这里(" + safecard.getAddress()+ ")，没想到周边的扒手和色狼还真不少呀。";
			if (StringUtil.isBlank(safecard.getMd5())) {
				Toast.makeText(this, "无法分享，请重新生成安全卡！", Toast.LENGTH_LONG)
						.show();
			} else {
//				sendReq(share_url, content, thumbBmp, menu_weixin_friend);
				UICore.eventTask(SafecardActiviy.this, SafecardActiviy.this, menu_weixin_friend, null, true);
			}
			break;
		case menu_tengxun:
			
			 content = content+"http://url.cn/";
			if (StringUtil.isBlank(safecard.getMd5())) {
				Toast.makeText(this, "无法分享，请重新生成安全卡！", Toast.LENGTH_LONG).show();
			} else {
				String accessToken = com.tencent.weibo.sdk.android.api.util.Util.getSharePersistent(getApplicationContext(), "ACCESS_TOKEN");
				if(accessToken==null || "".equals(accessToken)){
					Toast.makeText(SafecardActiviy.this,"请先授权", Toast.LENGTH_SHORT).show();
					long appid = Long.valueOf(UrlConfig.tx_wb_appId);
					String app_secket = UrlConfig.tx_wb_appsecret;
					auth(appid, app_secket);
				}else {
					isShare =false;
					if (tx_weiboAPI==null) {
						AccountModel account = new AccountModel(accessToken);
						tx_weiboAPI = new WeiboAPI(account);
					}
					tx_weiboAPI.getShortUrlFromLon(this, "json", share_url, this, null,BaseVO.TYPE_JSON);
					
				}
				
			}
			break;
		}
		return false;
	}

	@Override
	protected boolean onBackClick() {
		setResult(RESULT_OK, getIntent());
		finish();
		return false;
	}
	
	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setCoorType("bd09ll");	
		option.setAddrType("all");
		option.setScanSpan(0);
		option.setPriority(LocationClientOption.GpsFirst);
		option.setPoiNumber(10);
		option.disableCache(true);
		mLocClient.setLocOption(option);
	}

	/**
	 * locate to my position
	 */
	private void menuMyPosition() {
		loading();
		new Thread() {
			public void run() {
				setLocationOption();
				if (mLocClient != null && mLocClient.isStarted()) {
					mLocClient.requestLocation();
				} else {
					mLocClient.start();
					mLocClient.requestLocation();
				}
			};
		}.start();
	}

	@Override
	public void onResume() {
		mMapView.setVisibility(View.VISIBLE);
		mMapView.onResume();
		super.onResume();
	}

	@Override
	public void onPause() {
		mMapView.setVisibility(View.INVISIBLE);
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		mMapView.destroy();
		if (photoOriginUrlBitmap!=null) {
			if (photoOriginUrlBitmap.get()!=null) {
				photoOriginUrlBitmap.get().recycle();
			}
		}
		if (photoThumbUrlBitmap!=null) {
			if (photoThumbUrlBitmap.get()!=null) {
				photoThumbUrlBitmap.get().recycle();
			}
		}
		
		super.onDestroy();
	}

	@Override
	public boolean handleMessage(Message msg) {
		try {
			switch (msg.what) {
			case init_safe_cards:
				if (safecard != null) {
					empty_tv.setVisibility(View.GONE);
					findViewById(R.id.safe_map_layout).setVisibility(View.VISIBLE);
					precent_tv.setText("本地区危险指数：" + safecard.getPercent());
					address_tv.setText(safecard.getAddress());
					String desctiption = "本地区曾被曝发生过扒窃<font color=#54C26E>"
							+ safecard.getSub_count().getType1() + "</font>次，"
							+ "色狼<font color=#54C26E>"
							+ safecard.getSub_count().getType2() + "</font>次，"
							+ "拐卖<font color=#54C26E>"
							+ safecard.getSub_count().getType3() + "</font>次，"
							+ "iPhone丢失<font color=#54C26E>"
							+ safecard.getSub_count().getType4() + "</font>次。";
					if (safecard.getPercent() >= 50) {
						desctiption += "相比全国<font color=#54C26E>" + safecard.getPercent()
								+ "%</font>的地区，<font color=#54C26E>本地区更加安全</font>。";
					} else {
						desctiption += "相比全国<font color=#54C26E>" + (100 - safecard.getPercent())
								+ "%</font>的地区，<font color=#54C26E>本地区更加危险</font>。";
					}
					desctiption += " " + safecard.getDescription();
					type1_tv.setText("扒窃抢劫：" + safecard.getSub_count().getType1());
					type2_tv.setText("色狼变态：" + safecard.getSub_count().getType2());
					type3_tv.setText("走失拐卖：" + safecard.getSub_count().getType3());
					type4_tv.setText("苹果丢失：" + safecard.getSub_count().getType4());
					desctiption_tv.setText(Html.fromHtml(desctiption));
					if (!StringUtil.isBlank(safecard.getPhoto_origin_url())) {
						UICore.eventTask(this, this, task_photo_origin_url, null, false);
					}
					if (!StringUtil.isBlank(safecard.getPhoto_thumb_url())) {
						UICore.eventTask(this, this, task_photo_thumb_url, null, false);
					}
					Thread.sleep(500);
					handler.sendEmptyMessage(init_reports);
				} else {
					empty_tv.setVisibility(View.VISIBLE);
					findViewById(R.id.safe_map_layout).setVisibility(View.GONE);
				}
				break;
			case init_reports:
				showReports();
				break;
			case AppContext.LOCATE:
				current_latitude = app.latitude;
				current_longitude = app.longitude;
				UICore.eventTask(this, this, create_safe_card, null, true);
				break;
			case menu_sina:
				Toast.makeText(SafecardActiviy.this,"发送成功",Toast.LENGTH_LONG).show();
				break;
			case menu_weixin_contact:
				Toast.makeText(SafecardActiviy.this,"发送成功",Toast.LENGTH_LONG).show();
				break;
			case menu_weixin_friend:
				Toast.makeText(SafecardActiviy.this,"发送成功",Toast.LENGTH_LONG).show();
				break;	
			case menu_tengxun:
				Toast.makeText(SafecardActiviy.this,"发送成功",Toast.LENGTH_LONG).show();
				break;	
			case task_photo_origin_url:
				thumbBmp = photoOriginUrlBitmap.get();
				ScreenShot.savePic(photoOriginUrlBitmap.get(), photo_url);
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void execute(int mes, Object obj) {
		try {
			switch (mes) {
			case init_safe_cards:
				String result = HttpUtils.doGet(UrlConfig.safe_cards_detail + md5 + "?auth_token=" + AppContext.getInstance().getAuthToken());
				if (StringUtil.isNotBlank(result)) {
					Gson gson = new Gson();
					safecard = gson.fromJson(result, SafecardEntity.class);
				}
				handler.sendEmptyMessage(init_safe_cards);
				break;
			case create_safe_card:
				createSafecard();
				break;
			case menu_sina:
				ShareUtils.setHandle(handler, menu_sina);
				accessToken = AccessTokenKeeper.readAccessToken(SafecardActiviy.this);
				if (accessToken.isSessionValid()) {
					if (sinaWeiboAPI==null) {
						sinaWeiboAPI = new StatusesAPI(accessToken);
					}
//					sinaWeiboAPI.update(content, current_latitude+"", current_longitude+"", sinaRequestListener);
					sinaWeiboAPI.upload(content, photo_url, current_latitude+"", current_longitude+"", ShareUtils.sinaRequestListener);
				}
				break;
			case menu_weixin_contact:
				sendReq(share_url, content, photoThumbUrlBitmap.get(), menu_weixin_contact);
				break;
			case menu_weixin_friend:
				sendReq(share_url, content, photoThumbUrlBitmap.get(), menu_weixin_friend);
				break;
			case menu_tengxun:
//				ByteArrayOutputStream baos = new ByteArrayOutputStream();
//				thumbBmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
				
				tx_weiboAPI.addPicUrl(this, content+tx_shor_url+weibo_name, "json", current_longitude,current_latitude, safecard.getPhoto_origin_url(), 0, 0, this, null,BaseVO.TYPE_JSON);
				break;
			case task_photo_origin_url:
				photoOriginUrlBitmap = new WeakReference<Bitmap>(Utils.getBitmap(
						this, safecard.getPhoto_origin_url()));
				if (photoOriginUrlBitmap.get() != null) {
					handler.sendEmptyMessage(task_photo_origin_url);
				}
			case  task_photo_thumb_url:
				photoThumbUrlBitmap = new WeakReference<Bitmap>(Utils.getBitmap(
						this, safecard.getPhoto_thumb_url()));
//				if (photoOriginUrlBitmap.get() != null) {
//					handler.sendEmptyMessage(task_photo_origin_url);
//				}
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setting() {
		// UICore.eventTask(this, this, create_safe_card, null, true);
	}

	private void showReports() {
		double lat = safecard.getCoordinate().getLat();
		double lon = safecard.getCoordinate().getLon();
		if (lat != 0.0 && lon != 0.0) {
			GeoPoint pt = new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));
			mMapController.animateTo(pt);
		}
		Drawable drawable = getResources().getDrawable(Utils.getReportTypeIcon()[0]);
		ItemizedOverlay<OverlayItem> overlays = new ItemizedOverlay<OverlayItem>(
				drawable, mMapView);
		List<ReportEntity> reports = safecard.getReports();
		if (reports != null && !reports.isEmpty()) {
			for (int i = 0; i < reports.size() && i <= 100; i++) {
				ReportEntity report = reports.get(i);
				GeoPoint pt = new GeoPoint((int) (report.getCoordinate()
						.getLat() * 1E6), (int) (report.getCoordinate()
						.getLon() * 1E6));
				OverlayItem mOverlayIetm = new OverlayItem(pt, "",
						report.getText());
				if (report.getType_id() == 1) {
					mOverlayIetm.setMarker(marker1);
				} else if (report.getType_id() == 2) {
					mOverlayIetm.setMarker(marker2);
				} else if (report.getType_id() == 3) {
					mOverlayIetm.setMarker(marker3);
				} else if (report.getType_id() == 4) {
					mOverlayIetm.setMarker(marker4);
				} else {
					mOverlayIetm.setMarker(marker4);
				}
				overlays.addItem(mOverlayIetm);
			}
		}
		mMapView.getOverlays().clear();
		mMapView.getOverlays().add(overlays);
		mMapView.refresh();
	}

	private void createSafecard() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("auth_token", AppContext.getInstance().getAuthToken());
		paramsMap.put("lon", String.valueOf(current_longitude == 0.0 ? app.longitude : current_longitude));
		paramsMap.put("lat", String.valueOf(current_latitude == 0.0 ? app.latitude : current_latitude));
		paramsMap.put("from", "android_app");
		String result = HttpUtils.doPost(this, UrlConfig.safe_cards, paramsMap);
		if (StringUtil.isNotBlank(result)) {
			Gson gson = new Gson();
			safecard = gson.fromJson(result, SafecardEntity.class);
			if (safecard != null) {
				SafeCardTable st = new SafeCardTable(this);
				st.update(safecard);
			}
		}
		handler.sendEmptyMessage(init_safe_cards);
	}

	public void sendReq(String urls, String text, Bitmap bmp, int type) {

		String url = urls; // 收到分享的好友点击信息会跳转到这个地址去
		WXWebpageObject localWXWebpageObject = new WXWebpageObject();
		localWXWebpageObject.webpageUrl = url;
		WXMediaMessage localWXMediaMessage = new WXMediaMessage(
				localWXWebpageObject);
		localWXMediaMessage.title = "身边安全,一目了然";// 不能太长，否则微信会提示出错。不过博主没验证过具体能输入多长。
		localWXMediaMessage.description = text;

		localWXMediaMessage.thumbData = Utils.bmpToByteArray(bmp, true);
		SendMessageToWX.Req localReq = new SendMessageToWX.Req();
		localReq.transaction = System.currentTimeMillis() + "";
		localReq.message = localWXMediaMessage;
		// localReq.scene = isTimelineCb.isChecked() ?
		// SendMessageToWX.Req.WXSceneTimeline :
		// SendMessageToWX.Req.WXSceneSession;
		if (type == menu_weixin_friend) {
			localReq.scene = SendMessageToWX.Req.WXSceneTimeline;
		} else {
			localReq.scene = SendMessageToWX.Req.WXSceneSession;
		}

		api.sendReq(localReq);
	}
/**
 * 新浪微博授权
 * 
 * @author iris
 *
 */
	class SinaOAuthListener implements WeiboAuthListener {

		@Override
		public void onCancel() {
			
		}

		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
            String expires_in = values.getString("expires_in");
			final Oauth2AccessToken accessToken = new Oauth2AccessToken(token, expires_in);
			if (accessToken.isSessionValid()) {
				String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(accessToken.getExpiresTime()));
				System.out.println("+++++++++++++++" + "认证成功：token" + token + ";有效期：" + date);

				
								AccountAPI accountApi = new AccountAPI(accessToken);
				accountApi.getUid(new RequestListener() {
					
					@Override
					public void onIOException(IOException arg0) {
						System.out.println("---------------------" + arg0.getMessage());
					}
					
					@Override
					public void onError(WeiboException arg0) {
						System.out.println("-------------------------------------------------" + arg0.getMessage());
					}
					
					@Override
					public void onComplete(String arg0) {
						try {
							if (StringUtil.isNotBlank(arg0)) {
								JSONObject obj = new JSONObject(arg0);
								UsersAPI userApi = new UsersAPI(accessToken);
								userApi.show(Long.parseLong(obj.getString("uid")), new RequestListener() {
									
									@Override
									public void onIOException(IOException arg0) {
										
									}
									
									@Override
									public void onError(WeiboException arg0) {
										
									}
									
									@Override
									public void onComplete(String arg0) {
										if (StringUtil.isNotBlank(arg0)) {
											handler.post(new Runnable() {
												
												@Override
												public void run() {
													AccessTokenKeeper.keepAccessToken(SafecardActiviy.this, accessToken);
													UICore.eventTask(SafecardActiviy.this, SafecardActiviy.this, menu_sina, null, true);
												}
											});
										}
									}
								});
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
				
			}
		}

		@Override
		public void onError(WeiboDialogError error) {
			Toast.makeText(SafecardActiviy.this, "认证失败!", Toast.LENGTH_LONG).show();
			Log.i("debug", "onError:" + error.getMessage() );
		}

		@Override
		public void onWeiboException(WeiboException arg0) {
			Toast.makeText(SafecardActiviy.this, "认证失败!", Toast.LENGTH_LONG).show();
		}
	}
	
	private class BaseApiListener implements IRequestListener {
        private String mScope = "all";
        private Boolean mNeedReAuth = false;

        public BaseApiListener(String scope, boolean needReAuth) {
            mScope = scope;
            mNeedReAuth = needReAuth;
        }

        @Override
        public void onComplete(final JSONObject response, Object state) {
            doComplete(response, state);
        }

        protected void doComplete(JSONObject response, Object state) {
            try {
                int ret = response.getInt("ret");
                if (ret == 100030) {
                    if (mNeedReAuth) {
                        Runnable r = new Runnable() {
                            public void run() {
                                mTencent.reAuth(SafecardActiviy.this, mScope, new BaseUiListener());
                            }
                        };
                        SafecardActiviy.this.runOnUiThread(r);
                    }
                } else {
                	handler.post(new Runnable() {
						
						@Override
						public void run() {
							Toast.makeText(SafecardActiviy.this, "发送成功", Toast.LENGTH_LONG).show();
						}
					});
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.e("toddtest", response.toString());
            }

        }

        @Override
        public void onIOException(final IOException e, Object state) {
            showResult("IRequestListener.onIOException:", e.getMessage());
        }

        @Override
        public void onMalformedURLException(final MalformedURLException e, Object state) {
            showResult("IRequestListener.onMalformedURLException", e.toString());
        }

        @Override
        public void onJSONException(final JSONException e, Object state) {
            showResult("IRequestListener.onJSONException:", e.getMessage());
        }

        @Override
        public void onConnectTimeoutException(ConnectTimeoutException arg0, Object arg1) {
            showResult("IRequestListener.onConnectTimeoutException:", arg0.getMessage());

        }

        @Override
        public void onSocketTimeoutException(SocketTimeoutException arg0, Object arg1) {
            showResult("IRequestListener.SocketTimeoutException:", arg0.getMessage());
        }

        @Override
        public void onUnknowException(Exception arg0, Object arg1) {
            showResult("IRequestListener.onUnknowException:", arg0.getMessage());
        }

        @Override
        public void onHttpStatusException(HttpStatusException arg0, Object arg1) {
            showResult("IRequestListener.HttpStatusException:", arg0.getMessage());
        }

        @Override
        public void onNetworkUnavailableException(NetworkUnavailableException arg0, Object arg1) {
            showResult("IRequestListener.onNetworkUnavailableException:", arg0.getMessage());
        }
    }


	



	/**
	 * qq登录
	 */
	private void onQQLogin() {
		String SCOPE = "all";
		mTencent = AccessTokenKeeper.readTXQQToken(this, mTencent);
		if (!mTencent.isSessionValid()) {
			IUiListener listener = new BaseUiListener() {
				@Override
				protected void doComplete(JSONObject values) {
					try {
						AccessTokenKeeper.keepTXQQToken(SafecardActiviy.this, mTencent, values.getString("expires_in"));
					} catch (JSONException e) {
						e.printStackTrace();
					}
					if (mTencent.isSessionValid()&& mTencent.getOpenId() != null) {
						 onQQAddShare();
					}
				}
			};
			mTencent.login(this, SCOPE, listener);
		} else {
			// mTencent.logout(this);
			 onQQAddShare();
		}
	}
	
	/**
	 * 分享到QQ空间
	 */
	private void onQQAddShare() {
//		String photo_url = "http://www.zhianleida.com/safe_cards/share.jpg?key=9d387f33832511d2c13f8859352afbdf";
		Bundle parmas = new Bundle();
		parmas.putString("title", "身边安全,一目了然");// 必须。feeds的标题，最长36个中文字，超出部分会被截断。
		parmas.putString("url", share_url);//
//		parmas.putString("comment", ("QQ登陆SDK：测试comment" + new Date()));// 用户评论内容，也叫发表分享时的分享理由。禁止使用系统生产的语句进行代替。最长40个中文字，超出部分会被截断。
		parmas.putString("summary", content);// 所分享的网页资源的摘要内容，或者是网页的概要描述。//
												// 最长80个中文字，超出部分会被截断。
		parmas.putString("images", safecard.getPhoto_origin_url());// 所分享的网页资源的代表性图片链接"，请以http://开头，长度限制255字符。多张图片以竖线（|）分隔，目前只有第一张图片有效，图片规格100*100为佳。
		parmas.putString("type", "4");// 分享内容的类型。 4 是图片
		parmas.putString("nswb", "1");
		mTencent.requestAsync(Constants.GRAPH_ADD_SHARE, parmas,
				Constants.HTTP_POST, new BaseApiListener("add_share", true),
				null);

	}
		
	private void showResult(final String base, final String msg) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				destroyDialog();
				Toast.makeText(SafecardActiviy.this, base + msg,
						Toast.LENGTH_LONG).show();
			}
		});
	}

	private class BaseUiListener implements IUiListener {

		@Override
		public void onComplete(JSONObject response) {
			Log.d("debug", "doComplete---==>code:" + response.toString());
			doComplete(response);
		}

		protected void doComplete(JSONObject values) {

		}

		@Override
		public void onError(UiError e) {
			Log.d("debug", "UiError---===>" + e.errorCode + ", msg:"
					+ e.errorMessage + ", detail:" + e.errorDetail);
			showResult("onError:", "code:" + e.errorCode + ", msg:"
					+ e.errorMessage + ", detail:" + e.errorDetail);
		}

		@Override
		public void onCancel() {
			Log.d("debug", "onCancel---===>");
			showResult("onCancel", "");
		}
	}

	/**
	 * 腾讯微博授权
	 * 
	 * @param appid
	 * @param app_secket
	 */
	private void auth(final long appid, String app_secket) {
		final Context context = this.getApplicationContext();

		AuthHelper.register(this, appid, app_secket, new OnAuthListener() {

			@Override
			public void onWeiBoNotInstalled() {
				Toast.makeText(SafecardActiviy.this, "onWeiBoNotInstalled", Toast.LENGTH_SHORT).show();
				Intent i = new Intent(SafecardActiviy.this, Authorize.class);
				startActivity(i);
			}

			@Override
			public void onWeiboVersionMisMatch() {
				Toast.makeText(SafecardActiviy.this, "onWeiboVersionMisMatch", Toast.LENGTH_SHORT).show();
				Intent i = new Intent(SafecardActiviy.this, Authorize.class);
				startActivity(i);
			}

			@Override
			public void onAuthFail(int result, String err) {
				Toast.makeText(SafecardActiviy.this, "result : " + result, Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onAuthPassed(String name, WeiboToken token) {
				Toast.makeText(SafecardActiviy.this, "passed", Toast.LENGTH_SHORT).show();
				com.tencent.weibo.sdk.android.api.util.Util.saveSharePersistent(context, "ACCESS_TOKEN", token.accessToken);
				com.tencent.weibo.sdk.android.api.util.Util.saveSharePersistent(context, "EXPIRES_IN", String.valueOf(token.expiresIn));
				com.tencent.weibo.sdk.android.api.util.Util.saveSharePersistent(context, "OPEN_ID", token.openID);
				// Util.saveSharePersistent(context, "OPEN_KEY", token.omasKey);
				com.tencent.weibo.sdk.android.api.util.Util.saveSharePersistent(context, "REFRESH_TOKEN", "");
				// Util.saveSharePersistent(context, "NAME", name);
				// Util.saveSharePersistent(context, "NICK", name);
				com.tencent.weibo.sdk.android.api.util.Util.saveSharePersistent(context, "CLIENT_ID", UrlConfig.tx_wb_appId);
				com.tencent.weibo.sdk.android.api.util.Util.saveSharePersistent(context, "AUTHORIZETIME", String.valueOf(System.currentTimeMillis() / 1000l));
				if (tx_weiboAPI == null) {
					AccountModel account = new AccountModel(token.accessToken);
					tx_weiboAPI = new WeiboAPI(account);
				}
				tx_weiboAPI.getShortUrlFromLon(SafecardActiviy.this, "json", share_url, SafecardActiviy.this, null, BaseVO.TYPE_JSON);
			}
		});

		AuthHelper.auth(this, "");
	}

	boolean isShare;
	String tx_shor_url;

	/**
	 * 腾讯微博返回的结果
	 */
	@Override
	public void onResult(Object arg0) {
		if (arg0 != null) {
			ModelResult result = (ModelResult) arg0;
			if (result.isExpires()) {
				Toast.makeText(SafecardActiviy.this, result.getError_message(),
						Toast.LENGTH_SHORT).show();
			} else {
				if (result.isSuccess()) {
//					Toast.makeText(SafecardActiviy.this, "发送成功", 4000).show();
					Log.d("debug", "发送成功");
					if (!isShare) {
						isShare = true;
						Gson gson = new Gson();
						TXWeiboResultEntity txweibo = gson
								.fromJson(result.getObj().toString(),
										TXWeiboResultEntity.class);
						Log.d("debug", txweibo.data.getShort_url() + "发送成功");
						tx_shor_url = txweibo.data.getShort_url();
						// ByteArrayOutputStream baos = new
						// ByteArrayOutputStream();
						// thumbBmp.compress(Bitmap.CompressFormat.JPEG, 100,
						// baos);
						// tx_weiboAPI.addPic(this,
						// content+txweibo.data.getShort_url()+" ", "json",
						// current_longitude,current_latitude, thumbBmp, 0, 0,
						// this, null,BaseVO.TYPE_JSON);
						UICore.eventTask(SafecardActiviy.this,
								SafecardActiviy.this, menu_tengxun, null, true);
					} else {
						handler.sendEmptyMessage(menu_tengxun);
					}

				} else {
					Toast.makeText(SafecardActiviy.this, ((ModelResult) arg0).getError_message(), Toast.LENGTH_LONG).show();
				}
			}

		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (!mTencent.onActivityResult(requestCode, resultCode, data)) {
			
		}
	}
}
